import { Axios } from "../../api/axios"
const http = new Axios();
// @ts-ignore
export default {
	state: {
		classData: []
	},
	mutations: {
		SET_CLASSDATA: (state:any, data: Array<Object>) => {
			state.classData = data;
		},
		DELETE_CLASSDATA: (state:any, tag: Object) => {
			state.classData.splice(state.classData.indexOf(tag),1)
		},
		ADD_CLASSDATA:  (state:any, params: Object) => {
			state.classData.push({
				// @ts-ignore
				objectId: params['i'],
				// @ts-ignore
				classTitle: params['t']
			});
		}
	},
	actions: {
		/**
		 * 获取所有分类
		 * @param commit
		 */
		async getAllClass ({ commit }: any) {
			let data = await http.post({
				url: '/admin/getAllClass',
				params: { }
			});
			commit("SET_CLASSDATA",data.result);
		},
		
		/**
		 * 通过 mutations 中 DELETE_CLASSDATA 方法删除 vuex 的 classData 数据
		 * 同时发送ajax请求删除服务器的标签
		 * @param context
		 * @param currentTag 需要删除标签对象
		 */
		async deleteClass({ commit }: any, currentTag: Object) {
			await http.post({
				url: '/admin/deleteClassById',
				// @ts-ignore
				params: { id: currentTag.objectId }
			});
			commit("DELETE_CLASSDATA", currentTag);
		},
		
		/**
		 * 添加新的分类，push 数组，并向服务器添加数据
		 * @param commit
		 * @param tagTitle 分类标题
		 */
		async addClass({ commit }: any, tagTitle: string) {
			commit("ADD_CLASSDATA", { t: tagTitle, i: (await http.post({
					url: '/admin/addNewClass',
					params: { title:  tagTitle }
			})).result.objectId });
		}
	}
}